<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div{
            width: 200px;
            height: 200px;
            background: papayawhip;
            position: absolute;
            top: 0;
            left: 1px;
        }
    </style>
</head>
<body>
    <div></div>
    <script>
        var div = document.querySelector('div')
        div.onclick = function(){
            var timer = setInterval(function(){
                var lefth = div.offsetLeft
                var widthh = div.offsetTop
                if(widthh<500 && lefth<1000 && lefth >0){
                    div.style.left = lefth +10 +'px';
                }else if(widthh>=0 && lefth<=0){
                    div.style.top = widthh -10 +'px'
                    if(widthh<=0){
                        div.style.left = '1px'
                        clearInterval(timer)
                    }
                }

                if(lefth>=1000 && widthh<500){
                    // div.style.left = '1001px'
                    // clearInterval(timer) 
                    div.style.top = widthh +10 +'px'
                }else if(widthh>=500 && lefth>0){
                    div.style.left = lefth -10 +'px';
                }

            },30)
        }
    </script>
</body>
</html>